package com.example.demo07cache.component;

import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.ArrayList;
import java.util.List;

public class RedisScripts {
    public static final DefaultRedisScript<String> LOCK_LUA_SCRIPT = new DefaultRedisScript<>("if redis.call('set',KEYS[1],ARGV[1],'NX','PX',ARGV[2]) then return '1' else return '0' end", String.class);
    public static final DefaultRedisScript<String> UNLOCK_LUA_SCRIPT = new DefaultRedisScript<>("if redis.call('get',KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return '0' end", String.class);
    public static final DefaultRedisScript<String> DECR_TO_ZERO_LUA_SCRIPT = new DefaultRedisScript<>("if (tonumber(redis.call('get',KEYS[1]))>0) then return tostring(redis.call('decr',KEYS[1])) else return '-1' end", String.class);
    public static final DefaultRedisScript<String> DECR_STOCK_LUA_SCRIPT = new DefaultRedisScript<>("if (tonumber(redis.call('get',KEYS[1]))>=tonumber(ARGV[1])) then return tostring(redis.call('decrby',KEYS[1],ARGV[1])) else return '-1' end", String.class);
    public static final DefaultRedisScript<String> ADD_KEYS_LUA_SCRIPT = new DefaultRedisScript<>("for i=tonumber(ARGV[1]),1,-1 do\n" +
            "    redis.call('set',string.format(\"%s-%d\",KEYS[1],i),i*2,'NX','EX',ARGV[2])\n" +
            "end\n" +
            "return ARGV[1]", String.class);
    public static final DefaultRedisScript<String> BIT_COUNT_LUA_SCRIPT = new DefaultRedisScript<>("local count = 0\n" +
            "for i=tonumber(ARGV[2]),tonumber(ARGV[1]),-1 do\n" +
            "    count = count + redis.call('getbit',KEYS[1],i)\n" +
            "end\n" +
            "return tostring(count)", String.class);

    private static List<DefaultRedisScript<String>> scripts = new ArrayList<>();
    static {
        scripts.add(LOCK_LUA_SCRIPT);
        scripts.add(UNLOCK_LUA_SCRIPT);
        scripts.add(DECR_TO_ZERO_LUA_SCRIPT);
        scripts.add(DECR_STOCK_LUA_SCRIPT);
        scripts.add(ADD_KEYS_LUA_SCRIPT);
        scripts.add(BIT_COUNT_LUA_SCRIPT);
    }

    public static List<DefaultRedisScript<String >> getAllLuaScript() {
        return scripts;
    }
}
